import CryptoJS from 'crypto-js'
import { Base64 } from 'js-base64';

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */
export const uploadImageToOss = function(file, dir,bucket,region,token, accessKeyId, accessKeySecret) {
	if (!file) {
		uni.$tools.showToast('无效的图片资源')
		Promise.reject('无效的图片资源')
		return
	}
	let params = {}
	if(typeof file == 'string') {
		//文件本地路径
		params.filePath = file
	}
	else{
		//文件对象
		params.file = file
	}
	const aliyunFileKey = dir + "/" + new Date().getTime() + Math.floor(Math.random() * 150) + '.jpg';
	const aliyunServerURL = `https://${bucket}.${region}.aliyuncs.com`; //OSS地址，
	const accessid = accessKeyId;
	const policyBase64 = getPolicyBase64()
	//获取签名
	const signature = getSignature(policyBase64, accessKeySecret) 

	uni.$utils.showLoading('',true)
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: aliyunServerURL, //开发者服务器 url
			name: 'file', //必须填file
			...params,
			formData: {
				'key': aliyunFileKey,
				'policy': policyBase64,
				'OSSAccessKeyId': accessid,
				'signature': signature,
				'x-oss-security-token': token,
				'success_action_status': '200',
			},
			success: function(res) {
				uni.$utils.hideLoading()
				if (res.statusCode != 200) {
					reject('图片上传失败')
				}
				else{
					resolve(aliyunServerURL + '/' + aliyunFileKey);
				}
			},
			fail: function(err) {
				uni.$utils.hideLoading()
				reject(JSON.stringify(err));
			}
		})
	})
}

const getPolicyBase64 = function() {
	let date = new Date()
	date.setHours(date.getHours() + 87600)
	let srcT = date.toISOString()
	const policyText = {
		"expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
		"conditions": [
			["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5MB
		]
	}
	const policyBase64 = Base64.encode(JSON.stringify(policyText))
	return policyBase64
}
// 获取签名
const getSignature = function(policyBase64, accessKeySecret) {
	const wordArray = CryptoJS.enc.Utf8.parse(policyBase64)
	const keyWordArray = CryptoJS.enc.Utf8.parse(accessKeySecret)
	const signature = CryptoJS.enc.Base64.stringify(
		CryptoJS.HmacSHA1(wordArray, keyWordArray)
	)
	return signature
}
/**
 * 本地图片转base64
 * @param {string} fileUrl 本地图片路径
 * @return {Promise}
 */
const fileToBase64 = (fileUrl)=>{
	return new Promise((resolve,reject)=>{
		const reader = new FileReader()
		reader.onloadend = ()=>{
			resolve(reader.result)
		}
		reader.onerror = reject
		reader.readAsDataURL(fileUrl)
	})
}